package com.ygxsk.carhome.greendao;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;

import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.ygxsk.carhome.response.LoginBean;

import org.greenrobot.greendao.query.QueryBuilder;
import org.greenrobot.greendao.query.WhereCondition;

import java.util.List;

/*
 * @Author:itchenqi
 * @Time:2022-06-14  18:02
 * @Description:做用户登录信息 存储的 增删改查操作类；
 */
public class LoginInfoDaoManager {

    private static LoginInfoDaoManager sInstance;
    private DaoSession mDaoSession;

    public static LoginInfoDaoManager getInstance() {
        if (sInstance == null) {
            synchronized (LoginInfoDaoManager.class) {
                if (sInstance == null) {
                    sInstance = new LoginInfoDaoManager();
                }
            }
        }
        return sInstance;
    }


    //    public static DaoSession getDaoInstance() {
//
//        if (daoSession == null) {
//            daoSession = PropertyApplication.getInstance().();
//        }
//        //清空所有数据表的缓存数据
//        //daoSession.clear();
//        return daoSession;
//    }

    public void init(Context context) {

        //这里不查看日志信息
        //QueryBuilder.LOG_SQL = PropertyApplication.getInstance().isDebug;
        //QueryBuilder.LOG_VALUES = PropertyApplication.getInstance().isDebug;
        //这个是MySQLiteOpenHelper的调试日志；
        //MigrationHelper.DEBUG = PropertyApplication.getInstance().isDebug;

        //这种是不带迁移的
        //DaoMaster.DevOpenHelper devOpenHelper = new DaoMaster.DevOpenHelper(context, "workofflineinfo.db", null);
        //携带迁移
        MySQLiteOpenHelper devOpenHelper = new MySQLiteOpenHelper(context, "logininfo.db", null);
        SQLiteDatabase writableDatabase = devOpenHelper.getWritableDatabase();
        DaoMaster daoMaster = new DaoMaster(writableDatabase);
        mDaoSession = daoMaster.newSession();
    }


    /**
     * 插入一条登录数据
     */
    public void insertLoginInfo(LoginBean loginBean) {

        try {

            LoginInfo loginInfo = new LoginInfo();
            loginInfo.setCustomerId(Long.parseLong(loginBean.getCustomerId()));
            loginInfo.setUserToken(loginBean.getUserToken());
            loginInfo.setCommunityName(loginBean.getCommunityName());
            loginInfo.setCustomerInfoId(loginBean.getCustomerInfoId());
            loginInfo.setEmail(loginBean.getEmail());
            loginInfo.setSex(String.valueOf(loginBean.getSex()));
//            loginInfo.setConstellation(String.valueOf(loginBean.getConstellation()));
            loginInfo.setLoginName(loginBean.getLoginName());
            loginInfo.setTrueName(loginBean.getTrueName());
            loginInfo.setPhotoUrl(loginBean.getPhotoUrl());
//            loginInfo.setMaritalStatus(String.valueOf(loginBean.getMaritalStatus()));
//            loginInfo.setCenterPurviewList(JSON.toJSONString(loginBean.getCustomerCenterPurviewList()));

            //loginInfoDao.insert(loginInfo);
            //loginInfoDao.insertInTx(loginInfo);

            if (mDaoSession != null && mDaoSession.getLoginInfoDao() != null) {
                mDaoSession.getLoginInfoDao().insert(loginInfo);
            }

        } catch (Exception e) {

            e.printStackTrace();

//            LogUtils.d("itchen", "插入本地数据失败：" + e.getMessage());

        }


    }

    /**
     * 插入一条登录数据，或者如果存在的话  则替换掉它
     */
    public void insertOrReplaceLoginInfo(LoginBean loginBean) {

        try {

            LoginInfo loginInfo = new LoginInfo();
            loginInfo.setCustomerId(Long.parseLong(loginBean.getCustomerId()));
            loginInfo.setTimeStampCurrent(TimeUtils.getNowString());//填充当前插入的时间戳；
            loginInfo.setUserToken(loginBean.getUserToken());
            loginInfo.setCommunityName(loginBean.getCommunityName());
            loginInfo.setCustomerInfoId(loginBean.getCustomerInfoId());
            loginInfo.setEmail(loginBean.getEmail());
            loginInfo.setSex(String.valueOf(loginBean.getSex()));
//            loginInfo.setConstellation(String.valueOf(loginBean.getConstellation()));//星座
//            loginInfo.setMaritalStatus(String.valueOf(loginBean.getMaritalStatus()));//婚姻状态
//            loginInfo.setOccupation(loginBean.getOccupation());//职业信息；
//            loginInfo.setHobby(loginInfo.getHobby());//兴趣爱好
            loginInfo.setLoginName(loginBean.getLoginName());
            loginInfo.setPassword(loginInfo.getPassword());//密码
            loginInfo.setTrueName(loginBean.getTrueName());
            loginInfo.setPhotoUrl(loginBean.getPhotoUrl());
//            loginInfo.setCenterPurviewList(JSON.toJSONString(loginBean.getCustomerCenterPurviewList()));

            //loginInfoDao.insert(loginInfo);
            //loginInfoDao.insertInTx(loginInfo);

            if (mDaoSession != null && mDaoSession.getLoginInfoDao() != null) {
                mDaoSession.getLoginInfoDao().insertOrReplace(loginInfo);
            }

        } catch (Exception e) {

            e.printStackTrace();

//            LogUtils.d("itchen", "插入本地数据失败：" + e.getMessage());

        }

    }

    /**
     * 通过id删除数据
     */
    public void deleteloginInfoById(String customerId) {

        try {
            //do
            if (!TextUtils.isEmpty(customerId)) {

                if (mDaoSession != null && mDaoSession.getLoginInfoDao() != null) {

                    //查询单条，然后再删除；
                    LoginInfo loginInfo = mDaoSession.getLoginInfoDao().queryBuilder()
                            .where(LoginInfoDao.Properties.CustomerId.eq(customerId)).build().unique();

                    if (!ObjectUtils.isEmpty(loginInfo)) {
                        //第一种做法
                        //mDaoSession.getLoginInfoDao().deleteByKey(Long.parseLong(customerId));
                        //第二种做法
                        mDaoSession.getLoginInfoDao().delete(loginInfo);
                    }
                }

            }

        } catch (Exception e) {
            //catch
            e.printStackTrace();
        }


    }

    /**
     * 删除一条数据，删除单个数据；
     */
    public void deleteloginInfo(LoginInfo loginInfo) {

        try {

            if (mDaoSession != null && mDaoSession.getLoginInfoDao() != null) {
                mDaoSession.getLoginInfoDao().delete(loginInfo);
            }

        } catch (Exception e) {
            e.printStackTrace();
//            LogUtils.d("itchen", "删除一条本地数据失败：" + e.getMessage());
        }

    }


    /**
     * deleteAll()删除所有数据
     */
    //private void deleteAllDbBean(LoginInfo loginInfo) {
    public void deleteAllLoginInfoBean() {

        try {

            if (mDaoSession != null && mDaoSession.getLoginInfoDao() != null) {
                //loginInfoDao.deleteAll(loginInfo.getClass());
                mDaoSession.getLoginInfoDao().deleteAll();
            }

        } catch (Exception e) {
            e.printStackTrace();
//            LogUtils.d("itchen", "删除本地所有数据失败：" + e.getMessage());
        }

    }


    /**
     * update()修改本地数据
     */
    public void updateLoginInfoBean(LoginInfo loginInfo) {

        try {
            if (mDaoSession != null && mDaoSession.getLoginInfoDao() != null) {
                mDaoSession.getLoginInfoDao().update(loginInfo);
            }
        } catch (Exception e) {
            e.printStackTrace();
//            LogUtils.d("itchen", "修改本地所有数据失败：" + e.getMessage());
        }

    }

    /**
     * loadAll()查询本地所有数据
     */
    public List<? extends LoginInfo> queryAll(LoginInfo bean) {

        List<LoginInfo> beanList = null;

        try {
            //beanList = (List<LoginInfo>) loginInfoDao.loadAll(bean.getClass());
            if (mDaoSession != null && mDaoSession.getLoginInfoDao() != null) {
                beanList = (List<LoginInfo>) mDaoSession.getLoginInfoDao().loadAll();
            }
        } catch (Exception e) {
            e.printStackTrace();
//            LogUtils.d("itchen", "查询本地所有数据失败：" + e.getMessage());
        }

        return beanList;
    }

    /**
     * 单条件查询
     */
    public LoginInfo queryRawOneByUnique(String _customerId) {

        try {

            //do
            if (mDaoSession != null && mDaoSession.getLoginInfoDao() != null) {

                LoginInfo loginInfo = mDaoSession.getLoginInfoDao().queryBuilder()
                        .where(LoginInfoDao.Properties.CustomerId.eq(_customerId)).build().unique();//

                if (loginInfo != null) {
                    return loginInfo;
                } else {
                    return null;
                }

            }

        } catch (Exception e) {
            //catch
            e.printStackTrace();
        }

        return null;

    }

    /**
     * 查询单条数据.这个是否有更好的办法，我现在还不是很确定？ 这是一种 查询列表，返回第一个的方式；
     */
    public LoginInfo queryRawOne(String customerId) {


        try {
            //do
            if (mDaoSession != null && mDaoSession.getLoginInfoDao() != null) {

                //查询单条数据
                QueryBuilder queryBuilder = mDaoSession.getLoginInfoDao().queryBuilder();

                List<LoginInfo> resultBeans = queryBuilder.where(LoginInfoDao.Properties.CustomerId.eq(customerId)).list();

                if (resultBeans != null && !resultBeans.isEmpty()) {
                    return resultBeans.get(0);
                }
            }

        } catch (Exception e) {
            //catch
            e.printStackTrace();
        }

        return null;
    }


    /**
     * 根据条件查询本地所有数据
     * 调用时传值方法whereConditions
     * List<WhereCondition> whereConditions = new ArrayList<>();
     * whereConditions.add(StudentDao.Properties.Name.eq("小明"));
     * whereConditions.add(StudentDao.Properties.Age.eq(22));
     */
    public List<? extends LoginInfo> queryConditionAll(LoginInfo bean, List<WhereCondition> whereConditions)//
            throws ClassCastException {//

        List<LoginInfo> beanList = null;

        try {

            //QueryBuilder queryBuilder = loginInfoDao.queryBuilder(bean.getClass());
            QueryBuilder queryBuilder = mDaoSession.getLoginInfoDao().queryBuilder();

            //把条件循环加入
            if (null != whereConditions) {

                for (WhereCondition whereCondition : whereConditions) {
                    queryBuilder.where(whereCondition);
                }

            }

            beanList = queryBuilder.build().list();

        } catch (Exception e) {
            e.printStackTrace();
//            LogUtils.d("itchen", "按条件查询本地数据失败：" + e.getMessage());
        }

        return beanList;
    }


    /**
     * 根据原始 SQL 数据查询
     * 手输写 SQL 语句sqlConditions
     */
    private List<? extends LoginInfo> querySqlAll(LoginInfo bean, String sqlConditions) throws ClassCastException {

        List<LoginInfo> beanList = null;

        try {
            //查询条件
            WhereCondition.StringCondition stringCondition = new WhereCondition.StringCondition(sqlConditions);
            //查询QueryBuilder
            //QueryBuilder<LoginInfo> queryBuilder = (QueryBuilder<LoginInfo>) loginInfoDao.queryBuilder(bean.getClass());
            QueryBuilder<LoginInfo> queryBuilder = (QueryBuilder<LoginInfo>) mDaoSession.getLoginInfoDao().queryBuilder();
            //添加查询条件
            queryBuilder.where(stringCondition);

            beanList = queryBuilder.build().list();
        } catch (Exception e) {
            e.printStackTrace();
//            LogUtils.d("itchen", "sql按条件查询本地数据失败：" + e.getMessage());
        }

        return beanList;
    }


}
